import axios from 'axios'
import store from '@/store'

// create an axios instance
const service = axios.create({
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        // if (store.getters.token) {
        //     config.headers['X-Token'] = getToken()
        // }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        // return response.data;
      // dataAxios 是 axios 返回数据中的 data
      const dataAxios = response.data
      //若返回的是二进制blob对象
      if (response.headers['content-type']==='application/octet-stream'){
        return response
      }
      // 这个状态码是和后端约定的
      const {status} = dataAxios.meta
      if (status === undefined) {
        // 如果没有 status 代表这不是项目后端开发的接口
        return dataAxios
      } else {
        // 有 status 代表这是一个后端接口 可以进行进一步的判断
        switch (status) {
          case 200:
            // [ 示例 ] status === 200 代表没有错误
            return dataAxios
          case 605:
            // [ 示例 ] status === 605 业务错误
            errorCreate(`[ code: 605 ] ${dataAxios.meta.msg}: ${response.config.url}`)
            break
          case 604:
            // [ 示例 ] status === 604 接口权限错误
            errorCreate(`[ code: 604 ] ${dataAxios.meta.msg}: ${response.config.url}`)
            break
          default:
            // 不是正确的 code
            errorCreate(`错误： ${dataAxios.meta.msg}: ${response.config.url}`)
            break
        }
      }
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default service
